package com.hhf.springboot.controller;

import com.hhf.springboot.common.BaseResponse;
import com.hhf.springboot.common.ErrorCode;
import com.hhf.springboot.common.Result;
import com.hhf.springboot.exception.BusinessException;
import com.hhf.springboot.manager.FileManager;
import com.hhf.springboot.model.dto.file.UploadFileRequest;
import com.hhf.springboot.model.entity.User;
import com.hhf.springboot.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 文件接口
 *
 * @author hhf
 * @data 2024/9/26
 */
@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {

    @Resource
    private UserService userService;

    @Resource
    private FileManager fileManager;

    /**
     * 文件上传
     *
     * @param multipartFile
     * @param uploadFileRequest
     * @param request
     * @return
     */
    @PostMapping("/upload")
    public BaseResponse<String> uploadFile(@RequestPart("file") MultipartFile multipartFile,
                                           UploadFileRequest uploadFileRequest, HttpServletRequest request) {
        if (uploadFileRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String biz = uploadFileRequest.getBiz();
        User loginUser = userService.getLoginUser(request);
        // 文件上传
        String filepath = fileManager.uploadFile(multipartFile, biz, loginUser);
        return Result.success(filepath);

    }


    /**
     * 文件下载
     *
     * @param biz      文件类型
     * @param userId   用户目录
     * @param filename 文件名
     * @param response 响应对象
     */
    @GetMapping("/download/{biz}/{userId}/{filename}")
    public void downloadFile(@PathVariable("biz") String biz,
                             @PathVariable("userId") String userId,
                             @PathVariable("filename") String filename,
                             HttpServletResponse response) throws IOException {
        String filepath = String.format("/%s/%s/%s", biz, userId, filename);

        //下载文件
        fileManager.downloadFile(filepath, response);

    }
}
